from flask import Flask,render_template,request,redirect,url_for
from books import Books,DBSession
from sqlalchemy import or_

app=Flask(__name__)


@app.route('/booksList')
def booksList():
    session=DBSession()
    result=session.query(Books).all()
    return render_template('booksList.html', books= result)
#添加图书
@app.route('/addBook')
def addBook():
	return render_template('addBook.html')

@app.route('/doAddBook',methods=['GET','POST'])
def doAddBook():
	bookname=request.form['bookname']
	author=request.form['author']
	author_nationality=request.form['author_nationality']
	translator=request.form['translator']
	press=request.form['press']
	buyDate=request.form['buyDate']
	faimly_book=Books(bookname=bookname,author=author,author_nationality=author_nationality,translator=translator,press=press,buyDate=buyDate)
	#建立数据库连接
	session=DBSession()
	session.add(faimly_book)
	session.commit()
	session.close()
	return redirect(url_for('booksList'))

#查找图书
@app.route('/queryBook')
def queryBook():
	return render_template('queryBook.html')

@app.route('/doQueryBook',methods=['POST'])
def doQueryBook():
	bookname=request.form['bookname']
	print(bookname)
	author=request.form['author']
	session=DBSession()	
	result=session.query(Books).filter(or_(Books.bookname==bookname,Books.author==author)).all()
	# result=session.query(Books).filter(Books.bookname==bookname).all()
	session.commit()
	print(result)
	if result:
		return render_template('booksList.html',books=result)
	else:
		return "您查询的图书不存在"

@app.route('/deleteBook')
def deleteBook():
    id=request.args.get('id')
    session=DBSession()
    session.query(Books).filter(Books.id==id).delete()
    session.commit()
    return redirect(url_for('booksList'))

@app.route('/modifyBook')
def modifyBook():
	id=request.args.get('id')
	session=DBSession()
	book=session.query(Books).filter(Books.id==id).one()
	return render_template("modifyBook.html",book=book)

@app.route('/doModifyBook',methods=['POST'])
def doModifyBook():
    id=request.args.get('id')
    bookname=request.form['bookname']
    author=request.form['author']
    author_nationality=request.form['author_nationality']
    translator=request.form['translator']
    press=request.form['press']
    buyDate=request.form['buyDate']
    session=DBSession() 
    #修改数据
    session.query(Books).filter(Books.id==id).update({Books.bookname:bookname,Books.author:author,Books.author_nationality:author_nationality,Books.translator:translator,Books.press:press,Books.buyDate:buyDate})
    session.commit()
    return redirect(url_for('booksList'))


if __name__=="__main__":
	app.run(debug=True)